package com.zhangshujie.ShoppingSystem;

import java.util.Date;
import java.util.List;
import java.util.Scanner;


public class Main {
    private static FileManager fileManager = new FileManager();
    private static Scanner scanner = new Scanner(System.in);
    private static UserManager userManager = new UserManager();
    private static List<Customer> customers;
    private static ShoppingCart shoppingCart;
    private static ShoppingCartManager shoppingCartManager;
    static ProductManager productManager = new ProductManager(fileManager);


    public static void main(String[] args) {
        // 读取管理员和客户信息
        List<Admin> admins = fileManager.readAdmins();
        List<Customer> customers = fileManager.readCustomers();

        // 将客户添加到 UserManager
        for (Customer customer : customers) {
            userManager.addCustomer(customer);
        }

        // 预设管理员账户
        Admin admin = new Admin("1", "admin", "ynuinfo#777", "1234567890", "admin@example.com");
        if (admins.isEmpty()) {
            fileManager.addAdmin(admin);
        } else {
            admin = admins.get(0);
        }

        while (true) {
            System.out.println("欢迎使用购物系统");
            System.out.println("1. 管理员登录");
            System.out.println("2. 客户登录");
            System.out.println("3. 客户注册");
            System.out.println("4. 退出");
            System.out.print("请选择操作：");

            String choice = String.valueOf(scanner.nextInt());
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case "1":
                    adminLogin(admin);
                    break;
                case "2":
                    customerLogin();
                    break;
                case "3":
                    customerRegister();
                    break;
                case "4":
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新选择。");
            }
        }
    }

    private static void adminLogin(Admin admin) {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        if (admin.getUsername().equals(username) && admin.getPassword().equals(password)) {
            System.out.println("管理员登录成功！");
            adminMenu(admin);
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private static void customerLogin() {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        Customer customer = userManager.findCustomerByUsername(username);
        if (customer != null && customer.getPassword().equals(password)) {
            System.out.println("客户登录成功！");
            customerMenu(customer);
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private static void customerRegister() {
        System.out.print("请输入用户名（不少于5字符）：");
        String username = scanner.nextLine();
        System.out.print("请输入密码（大于8字符，组合大小写字母、数字和标点符号）：");
        String password = scanner.nextLine();
        System.out.print("请输入手机号：");
        String phoneNumber = scanner.nextLine();
        System.out.print("请输入邮箱：");
        String email = scanner.nextLine();
        String id = generateCustomerId(); // 生成唯一的客户ID
        String registrationTime = java.time.LocalDateTime.now().toString(); // 获取当前时间作为注册时间

        Customer newCustomer = new Customer(id, username, password, phoneNumber, email, registrationTime);
        userManager.addCustomer(newCustomer); // 添加到 UserManager
        fileManager.addCustomer(newCustomer);
        System.out.println("注册成功！");
    }

    private static int currentCustomerId = 1000; // 初始客户ID，可以根据需要设置初始值
    private static int currentProductId = 1000;
    private static String generateCustomerId() {
        currentCustomerId++;
        return String.valueOf(currentCustomerId);
    }

    private static String generateProductId() {
        currentProductId++;
        return String.valueOf(currentProductId);
    }

    private static void adminMenu(Admin admin) {
        while (true) {
            System.out.println("管理员菜单");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置客户密码");
            System.out.println("3. 列出所有客户信息");
            System.out.println("4. 删除客户信息");
            System.out.println("5. 查询客户信息");
            System.out.println("6. 商品管理");
            System.out.println("7. 退出登录");
            System.out.print("请选择操作：");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    System.out.print("请输入新密码：");
                    String newPassword = scanner.nextLine();
                    admin.changePassword(newPassword);
                    fileManager.addAdmin(admin); // 更新文件中的管理员信息
                    System.out.println("密码修改成功！");
                    break;
                case 2:
                    System.out.print("请输入客户用户名：");
                    String customerUsername = scanner.nextLine();
                    Customer customer = userManager.findCustomerByUsername(customerUsername);
                    if (customer != null) {
                        System.out.print("请输入新密码：");
                        String customerNewPassword = scanner.nextLine();
                        admin.resetCustomerPassword(customer, customerNewPassword);
                        fileManager.addCustomer(customer); // 更新文件中的客户信息
                        System.out.println("客户密码重置成功！");
                    } else {
                        System.out.println("客户不存在！");
                    }
                    break;
                case 3:
                    admin.listAllCustomers(userManager);
                    break;
                case 4:
                    System.out.println("请输入删除用户ID：");
                    String customerId = scanner.nextLine();
                    admin.deleteCustomer(userManager, customerId);
                    break;
                case 5:
                    System.out.println("请输入用户名或ID：");
                    String query = scanner.nextLine();
                    admin.searchCustomer(userManager, query);
                    break;
                case 6:
                    System.out.println("请选择操作：" );
                    System.out.println("1. 列出所有商品");
                    System.out.println("2. 添加商品 " );
                    System.out.println("3. 修改商品 ");
                    System.out.println("4. 删除商品 ");
                    System.out.println("5. 查询商品 ");
                    System.out.println("6. 退出");
                    int choice2 = scanner.nextInt();
                    switch (choice2) {
                        case 1:
                            productManager.listAllProducts();
                            break;
                        case 2:
                            String productID = generateProductId();
                            scanner.nextLine();
                            System.out.println("请输入商品信息：");
                            System.out.println("商品名称：");
                            String name = scanner.nextLine();
                            System.out.print("商品制造商：");
                            String manufacturer = scanner.nextLine();
                            System.out.print("生产日期：（例：2024-07-17）");
                            String productionDate = scanner.nextLine();
                            System.out.print("型号：");
                            String model = scanner.nextLine();
                            System.out.print("进货价格");
                            double purchasePrice = Double.parseDouble(scanner.nextLine());
                            System.out.print("零售价格");
                            double retailPrice = Double.parseDouble(scanner.nextLine());
                            System.out.print("数量");
                            int quantity = Integer.parseInt(scanner.nextLine());
                            Product newProduct = new Product(productID, name, manufacturer, model, productionDate, purchasePrice, retailPrice, quantity);
                            // 设置newProduct的属性
                            productManager.addProduct(newProduct);
                            break;
                        case 3:
                            System.out.println("请输入商品ID和更新后的信息：");
                            // 输入商品ID和更新后的信息并修改商品
                            productID = String.valueOf(scanner.nextInt());
                            scanner.nextLine(); // Consume newline
                            // 设置updatedProduct的属性
                            System.out.print("商品名称：");
                            String newName = scanner.nextLine();
                            System.out.print("商品制造商：");
                            manufacturer = scanner.nextLine();
                            System.out.print("生产日期：（例：2024-07-17）");
                            productionDate = scanner.nextLine();
                            System.out.print("型号：");
                            model = scanner.nextLine();
                            System.out.print("进货价格");
                            purchasePrice = Double.parseDouble(scanner.nextLine());
                            System.out.print("零售价格");
                            retailPrice = Double.parseDouble(scanner.nextLine());
                            System.out.print("数量");
                            quantity = Integer.parseInt(scanner.nextLine());
                            Product updatedProduct = new Product(productID, newName, manufacturer, model, productionDate, purchasePrice, retailPrice, quantity);
                            break;
                        case 4:
                            System.out.println("请输入要删除的商品ID：");
                            // 输入商品ID并删除商品
                            String deleteId = String.valueOf(scanner.nextInt());
                            productManager.deleteProduct(deleteId);
                            break;
                        case 5:
                            System.out.println("请输入查询条件：（没有则直接回车）");
                            // 输入查询条件并查询商品
                            System.out.print("商品名称：");
                            name = scanner.nextLine();
                            System.out.print("商品制造商");
                            manufacturer = scanner.nextLine();
                            System.out.print("商品零售价");
                            retailPrice = scanner.nextDouble();
                            productManager.searchProducts(name, manufacturer, retailPrice);
                            break;
                        case 6:
                            System.out.println("退出系统");
                            return;
                        default:
                            System.out.println("无效选择，请重新输入");
                    }
                    break;
                case 7:
                    return;
                default:
                    System.out.println("无效选择，请重新选择。");
            }
        }
    }

    private static void customerMenu(Customer customer) {
        while (true) {
            System.out.println("客户菜单");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 忘记密码");
            System.out.println("3. 购物");
            System.out.println("4. 查看购物历史");
            System.out.println("5. 退出登录");
            System.out.print("请选择操作：");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区

            switch (choice) {
                case 1:
                    System.out.print("请输入新密码：");
                    String newPassword = scanner.nextLine();
                    customer.changePassword(newPassword);
                    fileManager.addCustomer(customer); // 更新文件中的客户信息
                    System.out.println("密码修改成功！");
                    break;
                case 2:
                    System.out.print("请输入用户名：");
                    String username = scanner.nextLine();
                    System.out.print("请输入邮箱：");
                    String email = scanner.nextLine();
                    customer = userManager.findCustomerByUsername(username);
                    if (customer != null && customer.getEmail().equals(email)) {
                        String tempPassword = generateTempPassword();
                        customer.changePassword(tempPassword);
                        fileManager.addCustomer(customer); // 更新文件中的客户信息
                        System.out.println("临时密码已发送到您的邮箱：" + email);
                        // 这里可以添加发送邮件的逻辑
                    } else {
                        System.out.println("用户名或邮箱不匹配！");
                    }
                    break;
                case 3://ShoppingCartManage
                    System.out.println("请选择购物车操作：\n1. 加入商品\n 2. 移除商品\n 3. 修改商品数量\n 4. 结账\n 5. 查看购物历史\n 6. 返回主菜单\n");
                    int choice3 = scanner.nextInt();
                    scanner.nextLine(); // Consume newline

                    switch (choice3) {
                        case 1:
                            System.out.print("请输入商品编号：");
                            String productId = scanner.nextLine();
                            System.out.print("请输入数量：");
                            int quantity = scanner.nextInt();
                            scanner.nextLine(); // 清除缓冲区
                            Product product = productManager.findProductById(productId);
                            if (product != null) {
                                shoppingCartManager.addProductToCart(shoppingCart, product, quantity);
                            } else {
                                System.out.println("商品不存在！");
                            }
                            break;
                        case 2:
                            System.out.print("请输入商品编号：");
                            productId = scanner.nextLine();
                            product = productManager.findProductById(productId);
                            if (product != null) {
                                shoppingCartManager.removeProductFromCart(shoppingCart, product);
                            } else {
                                System.out.println("商品不存在！");
                            }
                            break;
                        case 3:
                            System.out.print("请输入商品编号：");
                            productId = scanner.nextLine();
                            System.out.print("请输入新的数量：");
                            quantity = scanner.nextInt();
                            scanner.nextLine(); // 清除缓冲区
                            product = productManager.findProductById(productId);
                            if (product != null) {
                                shoppingCartManager.updateProductQuantityInCart(shoppingCart, product, quantity);
                            } else {
                                System.out.println("商品不存在！");
                            }
                            break;
                        case 4:
                            System.out.print("请选择支付方式（支付宝、微信、银行卡）：");
                            String paymentMethod = scanner.nextLine();
                            shoppingCartManager.checkout(shoppingCart, paymentMethod);
                            break;
                        case 5:
                            shoppingCartManager.viewCart(shoppingCart);
                            break;
                        case 6:
                            return; // 返回主菜单
                        default:
                            System.out.println("无效选择，请重新输入");
                    }
                    break;
                case 4:
                    System.out.println("购物历史：");
                    for (String history : customer.getShoppingHistory()) {
                        System.out.println(history);
                    }
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择，请重新选择。");
            }
        }
    }


    private static String generateTempPassword() {
        // 生成临时密码的逻辑，例如使用随机字符串
        return "123456";
    }
    private static Customer findCustomerByUsername(String username) {
        for (Customer customer : customers) {
            if (customer.getUsername().equals(username)) {
                return customer;
            }
        }
        return null;
    }
}